package com.sda.renren;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingActivity;

public class MainActivity extends SlidingActivity {

	TextView text;
	TextView top;
	Document doc;
	Switch switch_mode;
	LinearLayout lay;
	String text1=null;
	String title;
	ProgressDialog dialog ;
	LoadTask task;
	String neirong;
	String biaoti;
	static int mIndex = 0;
	String num = String.valueOf(mIndex);
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(16974123);
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.activity_main);
		setBehindContentView(R.layout.behind);
		
		SlidingMenu menu = new SlidingMenu(getApplicationContext());
		menu.setMode(SlidingMenu.RIGHT); // 这个方法设置抽屉可以从哪边划出
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); // 这个方法设置触摸相应区域
		menu.setShadowWidthRes(R.dimen.shadow_width);// 设置边界绘制阴影宽度
		menu.setShadowDrawable(R.drawable.shadow);// 设置边界绘制阴影
		menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu.setFadeDegree(0.35f);

		menu.setMenu(R.layout.behind);
		
		final ActionBar bar = getActionBar();
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy1);StrictMode.setThreadPolicy(policy1);
		}
		
		
		text=(TextView)findViewById(R.id.text1);
		top=(TextView)findViewById(R.id.text2);
		switch_mode=(Switch)findViewById(R.id.sw_mode);
		
		lay=(LinearLayout)findViewById(R.id.lay);
		 
		
		
		
		 
		
		
		switch_mode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
				// TODO Auto-generated method stub
				if(isChecked){
					//text.setTextColor(Color.WHITE);
					lay.setBackgroundColor(Color.BLACK);
					
				}else{
					lay.setBackgroundColor(0);
				}
			}
		});
		
		boolean flag=false; 
		ConnectivityManager cwjManager=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
		if(cwjManager.getActiveNetworkInfo()!=null){
			flag=cwjManager.getActiveNetworkInfo().isAvailable(); 
			if(!flag){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
	            builder.setIcon(android.R.drawable.ic_dialog_alert);
	            builder.setTitle("提示");
	            builder.setMessage("当前网络不可用");
	            builder.show();
			}else{
				
				 task = new LoadTask(this);  
				 task.execute("http://zhan.renren.com/meiriyiwen?checked=true", num);	
				 
			}
		}
		
	}
		
	
	class LoadTask extends AsyncTask<String,Integer,String> {

		
		public LoadTask(Context context){  
			dialog = ProgressDialog.show(MainActivity.this, "", "Loading. Please wait...", true);
		}
		@Override
		protected String doInBackground(String... params) {//处理后台执行的任务，在后台线程执
			// TODO Auto-generated method stub
			
			//final TextView tv = null;  
			//publishProgress(0);//将会调用onProgressUpdate(Integer... progress)方法
			try {
				doc = Jsoup.parse(new URL("http://zhan.renren.com/meiriyiwen?checked=true"),5000);
				Log.e("doc", "on");
				
			} catch (MalformedURLException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
		Log.d("xjx", "params[0] = " + params[1]);
		int i=Integer.parseInt(params[1]);
		Log.d("xjx", "i = " + i);
		Elements es =doc.getElementsByClass("content");
		Elements et =doc.getElementsByClass("title");
		Element es1 =doc.getElementsByClass("title").get(i);//获取 class 标签为title 的html 源码
		Element et1 =doc.getElementsByClass("content").get(i);
		
		biaoti=es1.html();
		neirong=et1.html();
		Log.e("es", ""+biaoti);
		Log.e("et", ""+neirong);
		for(Element e1:et){
		    text1=e1.getElementsByTag("h2").text();
		    //top.setText(text1);
		   // Log.e("doc", "text");
		   
		}
		for(Element e:es){
		   title=e.getElementsByTag("p").text();
		   //text.setText(text1);
		  // Log.e("doc", ""+title);
		}
		
	    return text1;
	   }
		
		protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用，在ui线程执行  
		       // mProgressBar.setProgress(progress[0]);//更新进度条的进度  
			} 
		
		protected void onPostExecute(String result) {//后台任务执行完之后被调用，在ui线程执行  
	        
			ImageGetter imgGetter = new Html.ImageGetter() {

				@Override
				public Drawable getDrawable(String source) {
					   InputStream is=null;
					   try{
						   is=(InputStream)new URL(source).getContent();
						   Drawable drawable = Drawable.createFromStream(is, "src");
						   drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
						   is.close();
						   return drawable;
					   }catch (Exception e) {  
				            return null;  
				        }  
					   
				}
				
			};
			
				//Toast.makeText(MainActivity.this, "成功获取图片", Toast.LENGTH_LONG).show(); 
	            top.setText(Html.fromHtml(biaoti));
	            text.setText(Html.fromHtml(neirong, imgGetter, null));
	            Log.e("doc", ""+top);
	            dialog.cancel();
	          
	    }
		
		protected void onPreExecute () {//在 doInBackground(Params...)之前被调用，在ui线程执行  
	       // mImageView.setImageBitmap(null);  
	      //  mProgressBar.setProgress(0);//进度条复位  
			
			
	    }
		
		 protected void onCancelled () {//在ui线程执行  
	        // mProgressBar.setProgress(0);//进度条复位  
	     } 
}
	 
	
	 
		
	 @Override	
				
    public void onStart(){
    	super.onStart();
    	Log.i("Activity", "start");
    }
	
  
   
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_settings:
        	task = new LoadTask(this);  
        	mIndex++;
        	num = String.valueOf(mIndex);
			task.execute("http://zhan.renren.com/meiriyiwen?checked=true", num);	
        	break;
        case R.id.menu_list:
        	Intent i=new Intent();
        	i.setClass(MainActivity.this, VoiceActivity.class);
        	i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        	startActivity(i);
        	
        	break;
        case R.id.menu_reload:
        	Intent intent=new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
            intent.putExtra(Intent.EXTRA_TEXT, text.getText());
            startActivity(Intent.createChooser(intent, getTitle()));
        	}
        return super.onOptionsItemSelected(item);
        }

}
